package com.east.sng.utils;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.List;

/**
 * @author east
 * @date: 2021/12/28
 * @Description: param validation util
 **/
public class ValidationUtil {

    /**
     * 验证数据是否合法
     * @param br 验证数据结果
     * @throws ConstraintViolationException 验证数据不合法
     */
    public static void validateData(BindingResult br) throws ConstraintViolationException {
        if (br.hasErrors()) {
            StringBuffer stringBuffer = new StringBuffer();
            List<FieldError> errors = br.getFieldErrors();
            errors.forEach((item)->{
                stringBuffer.append(";"+item.getField()+":"+item.getDefaultMessage());
            });
            throw new ValidationException(stringBuffer.substring(1));
        }
    }

}
